//
//  WiiCalendarViewController.m
//  iFeller
//
//  Created by Wii on 15/12/21.
//  Copyright © 2015年 Wii. All rights reserved.
//

#import "WiiCalendarViewController.h"
#import "WiiHomeModel.h"
#import "WiiTaskDetailViewController.h"
#import "WiiTableHeader.h"
#import "WiiCalendarTableViewCell.h"

#define Identifier @"CalenDarCELL"
@interface WiiCalendarViewController () <JTCalendarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong) JTCalendarMenuView *calendarMenuView;
@property (nonatomic , strong) JTHorizontalCalendarView *calendarContentView;
@property (nonatomic , strong) JTCalendarManager *calendarManager;

@property (nonatomic , strong) UIImageView *navBarBG;
@property (nonatomic , strong) NSDate *todayDate;
@property (nonatomic , strong) NSDate *minDate;
@property (nonatomic , strong) NSDate *maxDate;
@property (nonatomic , strong) NSDate *dateSelected;
@property (nonatomic , strong) NSMutableDictionary *eventsByDate;

@property (nonatomic , strong) UITableView *mainTableView;
@property (nonatomic , strong) NSMutableArray *dataSource;
@property (nonatomic , strong) WiiHomeModel *model;
@end

@implementation WiiCalendarViewController
#pragma mark - View 生命周期

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    //去除导航栏下方的横线
    self.navBarBG.hidden = YES;
    // 隐藏返回按钮
    [self.navigationItem setHidesBackButton:YES];
    
    [self.model.sql openDataBase];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initUserInterFace];
    [self makeBackItem];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navBarBG.hidden = NO;
    
    [self.model.sql closeTheDataBase];
}
- (void)initUserInterFace{
    self.navBarBG = [WiiKit findHairlineImageViewUnder:self.navigationController.navigationBar];
    self.dataSource = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    _calendarManager = [JTCalendarManager new];
    _calendarManager.delegate = self;
    
    self.calendarContentView = [[JTHorizontalCalendarView alloc]initWithFrame:CGRectMake(0, 94, SCREEN_WIDTH, SCREEN_HEIGHT / 2 - 94)];
    self.calendarMenuView = [[JTCalendarMenuView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 30)];
    
    [self.view addSubview:self.calendarMenuView];
    [self.view addSubview:self.calendarContentView];
    // Generate random events sort by date using a dateformatter for the demonstration
    //    [self createRandomEvents];
    
    // Create a min and max date for limit the calendar, optional
    [self createMinAndMaxDate];
    
    [_calendarManager setMenuView:_calendarMenuView];
    [_calendarManager setContentView:_calendarContentView];
    [_calendarManager setDate:_todayDate];
    
    
}
#pragma mark - 返回按钮
- (void)makeBackItem{
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(WiiZero, WiiZero, WiiButtonSize, WiiButtonSize);
    [backButton setBackgroundImage:[UIImage imageNamed:@"BackArrow"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backItemHandleEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backItem;
}
- (void)backItemHandleEvent:(UIBarButtonItem *)item{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ChangeMode
- (void)changeModeAndGetDataWithDate:(NSString *)date{
    self.calendarManager.settings.weekModeEnabled = YES;
    self.calendarContentView.frame = CGRectMake(0, 94, SCREEN_WIDTH, 64);
    [self.view addSubview:self.mainTableView];
    self.dataSource = [NSMutableArray arrayWithArray:[self.model searchTaskInFinishTableWithDate:date]];
    [self.mainTableView reloadData];
}



#pragma mark UITableViewDelegate,UITableViewDataSource  
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WiiCalendarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier forIndexPath:indexPath];
    [cell getDataWith:[self.dataSource[indexPath.row] mutableCopy]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WiiTaskDetailViewController *taskDetailVC = [[WiiTaskDetailViewController alloc]init];
    taskDetailVC.dataSource = [self.dataSource[indexPath.row] mutableCopy];
    [self.navigationController pushViewController:taskDetailVC animated:YES];
}
#pragma mark - CalendarManager delegate

// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    // Today
    if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor blueColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Selected date
    else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor redColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    
    if([self haveEventForDay:dayView.date]){
        dayView.dotView.hidden = NO;
    }
    else{
        dayView.dotView.hidden = YES;
    }
}

- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
    _dateSelected = dayView.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    [self changeModeAndGetDataWithDate:[formatter stringFromDate:dayView.date]];
    NSLog(@"date:---------->%@",[formatter stringFromDate:dayView.date]);
    
    // Animation for the circleView
    dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
    [UIView transitionWithView:dayView
                      duration:.3
                       options:0
                    animations:^{
                        dayView.circleView.transform = CGAffineTransformIdentity;
                        [_calendarManager reload];
                    } completion:nil];
    
    
    // Load the previous or next page if touch a day from another month
    
    if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
            [_calendarContentView loadNextPageWithAnimation];
        }
        else{
            [_calendarContentView loadPreviousPageWithAnimation];
        }
    }
}

#pragma mark - CalendarManager delegate - Page mangement

// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
    return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}

- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
    //    NSLog(@"Next page loaded");
}

- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
    //    NSLog(@"Previous page loaded");
}

#pragma mark - Fake data (显示的月份区间：0代表当前月)

- (void)createMinAndMaxDate
{
    _todayDate = [NSDate date];
    
    // Min date will be 2 month before today
    _minDate = [_calendarManager.dateHelper addToDate:_todayDate months:0];
    
    // Max date will be 2 month after today
    _maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:2];
}

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    
    return dateFormatter;
}

- (BOOL)haveEventForDay:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
        return YES;
    }
    
    return NO;
    
}
#pragma mark - 日历标记方法
- (void)createRandomEvents
{
    _eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!_eventsByDate[key]){
            _eventsByDate[key] = [NSMutableArray new];
        }
        
        [_eventsByDate[key] addObject:randomDate];
    }
}

#pragma mark - setter/getter
- (UITableView *)mainTableView{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT - 200)];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.rowHeight = 88;
        _mainTableView.separatorStyle = NO;
        [_mainTableView registerNib:[UINib nibWithNibName:@"WiiCalendarTableViewCell" bundle:nil] forCellReuseIdentifier:Identifier];
    }
    return _mainTableView;
}
- (WiiHomeModel *)model{
    if (!_model) {
        _model = [[WiiHomeModel alloc]init];
    }
    return _model;
}
@end
